/**
 * 产品评论管理 API
 * 
 * 功能包括：
 * - 发布评论
 * - 获取评论列表
 * - 删除评论
 * - 编辑评论
 * - 评论点赞/踩
 * - 评论统计
 * - 审核管理
 */

import Router from 'koa-router';
import { pool } from '../../config/database';
import { authMiddleware } from '../../middleware/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { ApiResponse, JwtPayload } from '../../types';

const router = new Router({ prefix: '/api/reviews' });

// 评论接口类型定义
interface Review {
    id: number;
    product_id: number;
    user_id?: number;
    author: string;
    rating: number;
    comment: string;
    images?: string[];
    helpful_count: number;
    verified_purchase: boolean;
    status: 'pending' | 'approved' | 'rejected';
    is_anonymous: boolean;
    created_at: string;
    updated_at: string;
}

interface ReviewStats {
    total_reviews: number;
    average_rating: number;
    five_star_count: number;
    four_star_count: number;
    three_star_count: number;
    two_star_count: number;
    one_star_count: number;
}

// 获取产品评论列表
router.get('/product/:productId', async (ctx) => {
    try {
        const productId = parseInt(ctx.params.productId);
        const { page = 1, limit = 10, rating, sort = 'newest' } = ctx.query;

        if (isNaN(productId)) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '无效的产品ID'
            } as ApiResponse;
            return;
        }

            // 构建查询条件
    let whereClause = 'WHERE r.product_id = ? AND r.status = "approved"';
    const queryParams: any[] = [productId];

    if (rating && rating !== 'all') {
      whereClause += ' AND r.rating = ?';
      queryParams.push(parseInt(rating as string));
    }

            // 构建排序条件
    let orderClause = '';
    switch (sort) {
      case 'newest':
        orderClause = 'ORDER BY r.created_at DESC';
        break;
      case 'oldest':
        orderClause = 'ORDER BY r.created_at ASC';
        break;
      case 'rating_high':
        orderClause = 'ORDER BY r.rating DESC, r.created_at DESC';
        break;
      case 'rating_low':
        orderClause = 'ORDER BY r.rating ASC, r.created_at DESC';
        break;
      case 'helpful':
        orderClause = 'ORDER BY r.helpful_count DESC, r.created_at DESC';
        break;
      default:
        orderClause = 'ORDER BY r.created_at DESC';
    }

        // 分页参数
        const pageNum = Math.max(1, parseInt(page as string));
        const limitNum = Math.min(50, Math.max(1, parseInt(limit as string)));
        const offset = (pageNum - 1) * limitNum;

            // 获取评论列表，包含用户信息
    const [reviews] = await pool.query(
      `SELECT r.*, 
              u.nickname as user_nickname,
              u.avatar as user_avatar,
              u.email as user_email
       FROM product_reviews r
       LEFT JOIN users u ON r.user_id = u.id
       ${whereClause} 
       ${orderClause} 
       LIMIT ? OFFSET ?`,
      [...queryParams, limitNum, offset]
    ) as [RowDataPacket[], any];

            // 获取总数
    const [totalResult] = await pool.query(
      `SELECT COUNT(*) as total FROM product_reviews r ${whereClause}`,
      queryParams
    ) as [RowDataPacket[], any];

        const total = totalResult[0].total;

            // 处理图片字段和用户信息
    const processedReviews = reviews.map(review => ({
      ...review,
      images: review.images ? 
        (typeof review.images === 'string' ? JSON.parse(review.images) : review.images) : [],
      verified_purchase: Boolean(review.verified_purchase),
      is_anonymous: Boolean(review.is_anonymous),
      user_info: review.is_anonymous ? {
        nickname: '匿名用户',
        avatar: null,
        email: null,
        is_registered: false
      } : {
        nickname: review.user_nickname || review.author || '匿名用户',
        avatar: review.user_avatar || null,
        email: review.user_email || null,
        is_registered: review.user_id ? true : false
      }
    }));

        ctx.body = {
            success: true,
            data: {
                reviews: processedReviews,
                pagination: {
                    current_page: pageNum,
                    per_page: limitNum,
                    total_items: total,
                    total_pages: Math.ceil(total / limitNum)
                }
            }
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取评论失败：' + error.message
        } as ApiResponse;
    }
});

// 获取产品评论统计
router.get('/stats/:productId', async (ctx) => {
    try {
        const productId = parseInt(ctx.params.productId);

        if (isNaN(productId)) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '无效的产品ID'
            } as ApiResponse;
            return;
        }

        // 获取评论统计
        const [stats] = await pool.query(
            'SELECT * FROM product_review_stats WHERE product_id = ?',
            [productId]
        ) as [RowDataPacket[], any];

        if (stats.length === 0) {
            ctx.body = {
                success: true,
                data: {
                    product_id: productId,
                    total_reviews: 0,
                    average_rating: 0,
                    five_star_count: 0,
                    four_star_count: 0,
                    three_star_count: 0,
                    two_star_count: 0,
                    one_star_count: 0,
                    rating_distribution: []
                }
            } as ApiResponse;
            return;
        }

        const stat = stats[0];
        const ratingDistribution = [
            { rating: 5, count: stat.five_star_count, percentage: Math.round((stat.five_star_count / stat.total_reviews) * 100) },
            { rating: 4, count: stat.four_star_count, percentage: Math.round((stat.four_star_count / stat.total_reviews) * 100) },
            { rating: 3, count: stat.three_star_count, percentage: Math.round((stat.three_star_count / stat.total_reviews) * 100) },
            { rating: 2, count: stat.two_star_count, percentage: Math.round((stat.two_star_count / stat.total_reviews) * 100) },
            { rating: 1, count: stat.one_star_count, percentage: Math.round((stat.one_star_count / stat.total_reviews) * 100) }
        ];

        ctx.body = {
            success: true,
            data: {
                ...stat,
                average_rating: Math.round(stat.average_rating * 10) / 10, // 保留一位小数
                rating_distribution: ratingDistribution
            }
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取评论统计失败：' + error.message
        } as ApiResponse;
    }
});

// 发布评论
router.post('/', authMiddleware, async (ctx) => {
    try {
        const user = ctx.state.user as JwtPayload;
        const { product_id, rating, comment, images, author, is_anonymous } = ctx.request.body as any;

        // 验证必填字段
        if (!product_id || !rating || !comment) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '产品ID、评分和评论内容不能为空'
            } as ApiResponse;
            return;
        }

        if (rating < 1 || rating > 5) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '评分必须在1-5之间'
            } as ApiResponse;
            return;
        }

        // 检查产品是否存在
        const [products] = await pool.query(
            'SELECT id FROM products WHERE id = ?',
            [product_id]
        ) as [RowDataPacket[], any];

        if (products.length === 0) {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '产品不存在'
            } as ApiResponse;
            return;
        }

        // 检查用户是否已经评论过该产品
        const [existingReviews] = await pool.query(
            'SELECT id FROM product_reviews WHERE product_id = ? AND user_id = ?',
            [product_id, user.id]
        ) as [RowDataPacket[], any];

        if (existingReviews.length > 0) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '您已经评论过该产品了'
            } as ApiResponse;
            return;
        }

        // 检查是否为已验证购买（检查订单记录）
        let verifiedPurchase = false;
        try {
            const [orders] = await pool.query(
                `SELECT o.id FROM orders o 
         JOIN order_items oi ON o.id = oi.order_id 
         WHERE o.user_id = ? AND oi.product_id = ? AND o.status = 'completed'`,
                [user.id, product_id]
            ) as [RowDataPacket[], any];

            verifiedPurchase = orders.length > 0;
        } catch (error) {
            // 如果订单表不存在或查询失败，默认为未验证购买
            console.log('订单验证查询失败，设置为未验证购买:', error);
            verifiedPurchase = false;
        }

        // 获取用户信息以设置author
        let authorName = '匿名用户';
        
        // 如果用户选择匿名发送，直接使用匿名用户
        if (is_anonymous) {
            authorName = '匿名用户';
        } else if (user && user.id) {
            try {
                const [userInfo] = await pool.query(
                    'SELECT username, email FROM users WHERE id = ?',
                    [user.id]
                ) as [RowDataPacket[], any];
                
                if (userInfo.length > 0) {
                    // 优先使用用户数据库中的用户名，其次使用前端传的author，最后使用邮箱前缀
                    authorName = userInfo[0].username || 
                                author || 
                                (userInfo[0].email ? userInfo[0].email.split('@')[0] : '匿名用户');
                } else {
                    // 用户不存在，使用前端传的author
                    authorName = author || '匿名用户';
                }
            } catch (error) {
                console.log('获取用户信息失败，使用传入的author:', error);
                authorName = author || '匿名用户';
            }
        } else {
            // 未登录用户，使用前端传的author
            authorName = author || '匿名用户';
        }

        // 插入评论
        const [result] = await pool.query(
            `INSERT INTO product_reviews 
       (product_id, user_id, author, rating, comment, images, verified_purchase, status, is_anonymous) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [
                product_id,
                user.id,
                authorName,
                rating,
                comment,
                images ? JSON.stringify(images) : null,
                verifiedPurchase ? 1 : 0,
                'approved', // 可以设置为 'pending' 需要审核
                is_anonymous ? 1 : 0
            ]
        ) as [ResultSetHeader, any];

        ctx.body = {
            success: true,
            message: '评论发布成功',
            data: {
                review_id: result.insertId,
                verified_purchase: verifiedPurchase,
                author_name: authorName,
                is_anonymous: is_anonymous ? true : false,
                debug_info: {
                    user_id: user.id,
                    input_author: author,
                    final_author: authorName,
                    is_anonymous: is_anonymous
                }
            }
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '发布评论失败：' + error.message
        } as ApiResponse;
    }
});

// 获取用户的评论列表
router.get('/my-reviews', authMiddleware, async (ctx) => {
    try {
        const user = ctx.state.user as JwtPayload;
        const { page = 1, limit = 10 } = ctx.query;

        const pageNum = Math.max(1, parseInt(page as string));
        const limitNum = Math.min(50, Math.max(1, parseInt(limit as string)));
        const offset = (pageNum - 1) * limitNum;

            // 获取用户评论列表，包含产品信息和用户信息
    const [reviews] = await pool.query(
      `SELECT r.*, 
              p.name as product_name, 
              p.images as product_images,
              u.nickname as user_nickname,
              u.avatar as user_avatar,
              u.email as user_email
       FROM product_reviews r
       LEFT JOIN products p ON r.product_id = p.id
       LEFT JOIN users u ON r.user_id = u.id
       WHERE r.user_id = ?
       ORDER BY r.created_at DESC
       LIMIT ? OFFSET ?`,
      [user.id, limitNum, offset]
    ) as [RowDataPacket[], any];

        // 获取总数
        const [totalResult] = await pool.query(
            'SELECT COUNT(*) as total FROM product_reviews WHERE user_id = ?',
            [user.id]
        ) as [RowDataPacket[], any];

        const total = totalResult[0].total;

            // 处理数据
    const processedReviews = reviews.map(review => ({
      ...review,
      images: review.images ? 
        (typeof review.images === 'string' ? JSON.parse(review.images) : review.images) : [],
      product_images: review.product_images ? 
        (typeof review.product_images === 'string' ? JSON.parse(review.product_images) : review.product_images) : [],
      verified_purchase: Boolean(review.verified_purchase),
      is_anonymous: Boolean(review.is_anonymous),
      user_info: review.is_anonymous ? {
        nickname: '匿名用户',
        avatar: null,
        email: null,
        is_registered: false
      } : {
        nickname: review.user_nickname || review.author || '匿名用户',
        avatar: review.user_avatar || null,
        email: review.user_email || null,
        is_registered: review.user_id ? true : false
      }
    }));

        ctx.body = {
            success: true,
            data: {
                reviews: processedReviews,
                pagination: {
                    current_page: pageNum,
                    per_page: limitNum,
                    total_items: total,
                    total_pages: Math.ceil(total / limitNum)
                }
            }
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取用户评论失败：' + error.message
        } as ApiResponse;
    }
});

// 编辑评论
router.put('/:id', authMiddleware, async (ctx) => {
    try {
        const user = ctx.state.user as JwtPayload;
        const reviewId = parseInt(ctx.params.id);
        const { rating, comment, images } = ctx.request.body as any;

        if (isNaN(reviewId)) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '无效的评论ID'
            } as ApiResponse;
            return;
        }

        // 检查评论是否存在且属于当前用户
        const [reviews] = await pool.query(
            'SELECT * FROM product_reviews WHERE id = ? AND user_id = ?',
            [reviewId, user.id]
        ) as [RowDataPacket[], any];

        if (reviews.length === 0) {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '评论不存在或无权限编辑'
            } as ApiResponse;
            return;
        }

        // 检查评论是否在可编辑时间内（例如发布后24小时内）
        const review = reviews[0];
        const createdAt = new Date(review.created_at);
        const now = new Date();
        const hoursDiff = (now.getTime() - createdAt.getTime()) / (1000 * 60 * 60);

        if (hoursDiff > 24) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '评论发布超过24小时，无法编辑'
            } as ApiResponse;
            return;
        }

        // 验证评分
        if (rating && (rating < 1 || rating > 5)) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '评分必须在1-5之间'
            } as ApiResponse;
            return;
        }

        // 构建更新字段
        const updateFields = [];
        const updateValues = [];

        if (rating !== undefined) {
            updateFields.push('rating = ?');
            updateValues.push(rating);
        }

        if (comment !== undefined) {
            updateFields.push('comment = ?');
            updateValues.push(comment);
        }

        if (images !== undefined) {
            updateFields.push('images = ?');
            updateValues.push(images ? JSON.stringify(images) : null);
        }

        if (updateFields.length === 0) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '没有要更新的字段'
            } as ApiResponse;
            return;
        }

        updateFields.push('updated_at = CURRENT_TIMESTAMP');
        updateValues.push(reviewId);

        // 更新评论
        await pool.query(
            `UPDATE product_reviews SET ${updateFields.join(', ')} WHERE id = ?`,
            updateValues
        );

        ctx.body = {
            success: true,
            message: '评论更新成功'
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '更新评论失败：' + error.message
        } as ApiResponse;
    }
});

// 删除评论
router.delete('/:id', authMiddleware, async (ctx) => {
    try {
        const user = ctx.state.user as JwtPayload;
        const reviewId = parseInt(ctx.params.id);

        if (isNaN(reviewId)) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '无效的评论ID'
            } as ApiResponse;
            return;
        }

        // 检查评论是否存在且属于当前用户
        const [reviews] = await pool.query(
            'SELECT * FROM product_reviews WHERE id = ? AND user_id = ?',
            [reviewId, user.id]
        ) as [RowDataPacket[], any];

        if (reviews.length === 0) {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '评论不存在或无权限删除'
            } as ApiResponse;
            return;
        }

        // 删除评论
        await pool.query(
            'DELETE FROM product_reviews WHERE id = ? AND user_id = ?',
            [reviewId, user.id]
        );

        ctx.body = {
            success: true,
            message: '评论删除成功'
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '删除评论失败：' + error.message
        } as ApiResponse;
    }
});

// 评论点赞/取消点赞
router.post('/:id/helpful', authMiddleware, async (ctx) => {
    try {
        const user = ctx.state.user as JwtPayload;
        const reviewId = parseInt(ctx.params.id);
        const { helpful } = ctx.request.body as { helpful: boolean };

        if (isNaN(reviewId)) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '无效的评论ID'
            } as ApiResponse;
            return;
        }

        // 检查评论是否存在
        const [reviews] = await pool.query(
            'SELECT id FROM product_reviews WHERE id = ?',
            [reviewId]
        ) as [RowDataPacket[], any];

        if (reviews.length === 0) {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '评论不存在'
            } as ApiResponse;
            return;
        }

        // 这里可以实现用户点赞记录表，防止重复点赞
        // 简化版本：直接更新helpful_count
        if (helpful) {
            await pool.query(
                'UPDATE product_reviews SET helpful_count = helpful_count + 1 WHERE id = ?',
                [reviewId]
            );
        } else {
            await pool.query(
                'UPDATE product_reviews SET helpful_count = GREATEST(helpful_count - 1, 0) WHERE id = ?',
                [reviewId]
            );
        }

        ctx.body = {
            success: true,
            message: helpful ? '点赞成功' : '取消点赞成功'
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '操作失败：' + error.message
        } as ApiResponse;
    }
});

// 获取最新评论（首页显示用）
router.get('/latest', async (ctx) => {
    try {
        const { limit = 10 } = ctx.query;
        const limitNum = Math.min(20, Math.max(1, parseInt(limit as string)));

            const [reviews] = await pool.query(
      `SELECT r.*, 
              p.name as product_name, 
              p.images as product_images,
              u.nickname as user_nickname,
              u.avatar as user_avatar,
              u.email as user_email
       FROM product_reviews r
       LEFT JOIN products p ON r.product_id = p.id
       LEFT JOIN users u ON r.user_id = u.id
       WHERE r.status = 'approved'
       ORDER BY r.created_at DESC
       LIMIT ?`,
      [limitNum]
    ) as [RowDataPacket[], any];

            const processedReviews = reviews.map(review => ({
      ...review,
      images: review.images ? 
        (typeof review.images === 'string' ? JSON.parse(review.images) : review.images) : [],
      product_images: review.product_images ? 
        (typeof review.product_images === 'string' ? JSON.parse(review.product_images) : review.product_images) : [],
      verified_purchase: Boolean(review.verified_purchase),
      user_info: {
        nickname: review.user_nickname || review.author || '匿名用户',
        avatar: review.user_avatar || null,
        email: review.user_email || null,
        is_registered: review.user_id ? true : false
      }
    }));

        ctx.body = {
            success: true,
            data: processedReviews
        } as ApiResponse;
    } catch (error: any) {
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取最新评论失败：' + error.message
        } as ApiResponse;
    }
});

export default router; 